﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using DevExpress.XtraCharts;
using Lamex.Base;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using System.IO;
using Lamex.Interface;
using Lamex.mDashboard.Model;
using Lamex.mDashboard.BLL;
using Lamex.Library.CommonClass;


namespace Lamex.mDashboard.UI
{
    public partial class FrmPPC_Utilization : frmBaseChild
    {
        public FrmPPC_Utilization()
        {
            InitializeComponent();
            GetInitialize();
        }

        private void FrmPPC_Utilization_Load(object sender, EventArgs e)
        {
            try { this.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
        }
        public DataTable GetThiness()
        {
            DataTable dt = new DataTable();
            string sqlThickness = @" select distinct Mat_Thickness from [StorageManager].[dbo].[T3_Material] order by Mat_Thickness";
            dt = BaseBuildSql.GetDataTableBySql(sqlThickness);
            return dt;
        }
        private void GetInitialize()
        {

            //string sqlThickness = @" select distinct Mat_Thickness from [StorageManager].[dbo].[T3_Material] order by Mat_Thickness";
            DataTable dtThickness = GetThiness();//BaseBuildSql.GetDataTableBySql(sqlThickness);
            ccbeThickness.Properties.DataSource = dtThickness;
            ccbeThickness.Properties.DisplayMember = "Mat_Thickness";
            ccbeThickness.Properties.ValueMember = "Mat_Thickness";

            var formatString = "yyyy-MM";
            dateEdit1.Properties.DisplayFormat.FormatString = "yyyy-MM";
            dateEdit1.Properties.Mask.EditMask = formatString;
            dateEdit1.Properties.VistaCalendarInitialViewStyle = DevExpress.XtraEditors.VistaCalendarInitialViewStyle.YearView;
            dateEdit1.Properties.VistaCalendarViewStyle = DevExpress.XtraEditors.VistaCalendarViewStyle.YearView;

            dateEdit2.Properties.DisplayFormat.FormatString = "yyyy-MM";
            dateEdit2.Properties.Mask.EditMask = formatString;
            dateEdit2.Properties.VistaCalendarInitialViewStyle = DevExpress.XtraEditors.VistaCalendarInitialViewStyle.YearView;
            dateEdit2.Properties.VistaCalendarViewStyle = DevExpress.XtraEditors.VistaCalendarViewStyle.YearView;

        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        public override void DoView(Lamex.Interface.IButtonInfo sender)
        {
            //using (DevExpress.Utils.WaitDialogForm wdf = new DevExpress.Utils.WaitDialogForm("报表正在加载中", "请稍后......", new Size(400, 80)))
            //{
            SplashScreenTool.ShowSplashScreen(typeof(WaitForm1));
            string strThiness = ccbeThickness.Text;
            if (string.IsNullOrEmpty(dateEdit1.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("开始日期不能为空", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(dateEdit2.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("结束日期不能为空", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(strThiness))
            {
                for (int i = 0; i < GetThiness().Rows.Count; i++)
                {
                    strThiness += GetThiness().Rows[i][0].ToString() + ",";
                }
                strThiness = strThiness.Substring(0, strThiness.Length - 1);
            }
            List<string> lst1 = new List<string>();
            List<string> lst2 = new List<string>();
            lst1.Add("3");//标识为图表1-gridview
            lst1.Add(dateEdit1.Text + "-01");//年份
            lst1.Add(dateEdit2.Text + "-01");//月份
            lst1.Add(txtCode.Text);//物料代码
            lst1.Add(strThiness);//厚度 

            lst2.Add("4");//标识为图表1
            lst2.Add(dateEdit1.Text + "-01");//年份
            lst2.Add(dateEdit2.Text + "-01");//月份
            lst2.Add(txtCode.Text);//物料代码
            lst2.Add(strThiness);//厚度 
            DataTable dt = Lamex.Base.BaseBuildSql.GetProDataTable("p_PPC_HPOReport", lst1);
            DataTable dt2 = Lamex.Base.BaseBuildSql.GetProDataTable("p_PPC_HPOReport", lst2);
            //转换生成新的数据源
            if (dt.Rows.Count > 0)
            {
                GetNewDataTable(dt);//生成gridview数据源
                GetNewDataTableChart(dt2);//生成chartcontrol数据源
                GetChart001(dt2);
            }
            //dt.Columns.Remove("Colums");//去掉临时列
            gridControl1.DataSource = dt;//显示GridView表格
            gridView1.BestFitColumns();
            this.gridView1.OptionsView.ColumnAutoWidth = false;
            base.DoView(sender);
            Save_Click_Ratio();
            SplashScreenTool.CloseSplashScreen();
            // }
        }

        private void GetChart001(DataTable dt2)
        {
            //趋势图
            chart001.Series.Clear();
            DataView dataview = dt2.DefaultView;//需要传dt值过来，前80%的值
            DataTable dt3 = dataview.ToTable(true, "COMPONENT_NAME", "Description");
            for (int i = 0; i < dt3.Rows.Count; i++)
            {
                DataTable newdt = new DataTable();
                newdt = dt2.Clone();//需要到dt2的表结构
                DataRow[] rows = dt2.Select("COMPONENT_NAME='" + dt3.Rows[i]["COMPONENT_NAME"].ToString() + "'");//绑定数据源
                foreach (DataRow row in rows)
                {
                    newdt.Rows.Add(row.ItemArray);
                }
                //string str = dt3.Rows[i]["COMPONENT_NAME"].ToString() + (string.IsNullOrEmpty(dt3.Rows[i]["Description"].ToString()) ? dt3.Rows[i]["Description"].ToString()
                //  : dt3.Rows[i]["Description"].ToString().Substring(0, 11));
                Series seriesAuto3 = new Series(dt3.Rows[i]["COMPONENT_NAME"].ToString(), ViewType.Line);
                seriesAuto3.DataSource = newdt;//绑定数据源
                seriesAuto3.ArgumentScaleType = ScaleType.Qualitative;//指定X轴坐标以定性方式表示
                //名称
                seriesAuto3.ArgumentDataMember = "Months";//指定X轴绑定列
                seriesAuto3.ValueScaleType = ScaleType.Numerical;//指定Y轴以数字方式标记
                //取值字段 
                seriesAuto3.ValueDataMembers.AddRange(new string[] { "sums" });//指定Y轴绑定列  
                seriesAuto3.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
                seriesAuto3.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True;//每个点都显示数据
                this.chart001.Series.Add(seriesAuto3);
            }


            //横标题设置
            chart001.Titles.Clear();
            ChartTitle titles = new ChartTitle();            //声明标题
            titles.Text = "用量排前的板材利用率趋势图";                   //名称
            //titles.TextColor = System.Drawing.Color;       //颜色
            titles.Indent = 1;                                //设置距离  值越小柱状图就越大
            titles.Font = new Font("Tahoma", 12, FontStyle.Bold);            //设置字体
            titles.Dock = ChartTitleDockStyle.Top;           //设置对齐方式
            titles.Indent = 0;
            titles.Alignment = StringAlignment.Center;       //居中对齐
            chart001.Titles.Add(titles);                     //添加标题 
        }

        private void GetNewDataTable(DataTable dt)
        {
           
            //double sumObject = Convert.ToDouble(dt.Compute("sum(Sums)", "TRUE")); //对列SUMS求总和
            //从第二列动态数据计算
            //dt.Columns.Add("Colums", typeof(string));//存放物料编号和描述合并字段
            for (int i = 2; i < dt.Columns.Count-1; i++)
            {
                /* 权重计算逻辑 
                 * （数量*利用率）求和）/数量求和=权重利用率%
                 */
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    if (dt.Columns[i].ColumnName.ToString() == "Sums" || dt.Columns[i].ColumnName.ToString() == "Sums_QTY")
                        dt.Rows[j]["Sums"] = Math.Round(Convert.ToDouble(dt.Rows[j]["Sums"]) / Convert.ToDouble(dt.Rows[j]["Sums_QTY"]) ,2);
                    else
                        dt.Rows[j][i] = Math.Round(Convert.ToDouble(dt.Rows[j][i]),2);

                  //  dt.Rows[j]["Colums"] = dt.Rows[j]["COMPONENT_NAME"].ToString()
                  //+ (string.IsNullOrEmpty(dt.Rows[j]["Description"].ToString()) ? dt.Rows[j]["Description"].ToString()
                  //: dt.Rows[j]["Description"].ToString().Substring(0, 11));
                }

            }
            dt.Columns.Remove("Sums_QTY");

        }
        private void GetNewDataTableChart(DataTable dt)
        {
            //double sumObject = Convert.ToDouble(dt.Compute("sum(Sums)", "TRUE")); //对列SUMS求总和
            //计算sums列利用率

            for (int j = 0; j < dt.Rows.Count; j++)
            {
                dt.Rows[j]["sums"] = Math.Round(Convert.ToDouble(dt.Rows[j]["sums"].ToString()) / Convert.ToDouble(dt.Rows[j]["sums_Qty"].ToString()), 2);
            }
        }

        public override void DoExport(IButtonInfo sender)
        {
            ExportToExcel(gridControl1, chart001);
        }
        /// <summary>
        /// DevExpress通用导出Excel,支持多个控件同时导出在同一个Sheet表
        /// eg:ExportToXlsx("",gridControl1,gridControl2);
        /// 将gridControl1和gridControl2的数据一同导出到同一张工作表
        /// </summary>
        /// <param name="title">文件名</param>
        /// <param name="panels">控件集</param>
        public void ExportToExcel(params IPrintable[] panels)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = "报表";
            saveFileDialog.Title = "导出Excel";
            saveFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls";
            DialogResult dialogResult = saveFileDialog.ShowDialog();
            if (dialogResult == DialogResult.Cancel)
                return;
            string FileName = saveFileDialog.FileName;
            PrintingSystem ps = new PrintingSystem();
            CompositeLink link = new CompositeLink(ps);
            ps.Links.Add(link);
            foreach (IPrintable panel in panels)
            {
                link.Links.Add(CreatePrintableLink(panel));
            }
            link.Landscape = true;//横向           
            //判断是否有标题，有则设置         
            //link.CreateDocument(); //建立文档
            try
            {
                int count = 1;
                //在重复名称后加（序号）
                while (File.Exists(FileName))
                {
                    if (FileName.Contains(")."))
                    {
                        int start = FileName.LastIndexOf("(");
                        int end = FileName.LastIndexOf(").") - FileName.LastIndexOf("(") + 2;
                        FileName = FileName.Replace(FileName.Substring(start, end), string.Format("({0}).", count));
                    }
                    else
                    {
                        FileName = FileName.Replace(".", string.Format("({0}).", count));
                    }
                    count++;
                }
                if (FileName.LastIndexOf(".xlsx") >= FileName.Length - 5)
                {
                    XlsxExportOptions options = new XlsxExportOptions();
                    link.ExportToXlsx(FileName, options);
                }
                else
                {
                    XlsExportOptions options = new XlsExportOptions();
                    link.ExportToXls(FileName, options);
                }
                if (DevExpress.XtraEditors.XtraMessageBox.Show("保存成功，是否打开文件？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(FileName);//打开指定路径下的文件
            }
            catch (Exception ex)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            }
        }

        PrintableComponentLink CreatePrintableLink(IPrintable printable)
        {
            ChartControl chart = printable as ChartControl;
            if (chart != null)
                chart.OptionsPrint.SizeMode = DevExpress.XtraCharts.Printing.PrintSizeMode.Stretch;
            PrintableComponentLink printableLink = new PrintableComponentLink() { Component = printable };
            return printableLink;
        }

        private void Save_Click_Ratio()
        {
            Sys_P_ReportInfo model = new Sys_P_ReportInfo();
            model.MODULE = "PPC";//模块名
            model.REPORT_NAME = "HPO利用率报表";//报表名称
            model.IP = System.Environment.UserName;//当前用户名
            model.CREATE_TS = DateTime.Now;//创建时间
            model.USERNAME = Lamex.Common.Loginer.CurrentUser.Account;//修改人
            if (BaseFactory<Sys_P_Report>.Instance.Insert(model))
            {              

            }
        }
    }
}
